﻿using System.Collections;
using System.ComponentModel;
using BomComparison.Core.Interface;
using BomComparison.Core.Model;
using Infrastructure.Helpers;
using Module.Common.EventAggregator;

namespace BomComparisonModule.ViewModels
{
    public class FileSelectBrowserViewModel : BindableBase
    {
        #region 私有变量
        private IUnityContainer _container;
        private readonly IEventAggregator _ea;
        private readonly IRegionManager _regionManager;
        private readonly IDialogService _dialogService;
        private readonly IEnumerable<IBomComparisonService> _comparisonServices;
        //private readonly IBomComparisonCoordinator _coordinator;
        private readonly IExcelReader _excelReader;
        private readonly IExcelWriter _excelWriter;
        private string _message = "Message to Send";
        private string _title = "Prism Unity Application";

        private string _outPutPath;

        private string _filePath1;
        private int _titleRow1 = 5;
        private int _partNumberCol1 = 2;
        private int _partQtyCol1 = 5;
        private int _partRefDesCol1 = 7;
        private int _partDescriptionCol1 = 4;

        private string _filePath2;
        private int _titleRow2 = 5;
        private int _partNumberCol2 = 2;
        private int _partQtyCol2 = 5;
        private int _partRefDesCol2 = 7;
        private int _partDescriptionCol2 = 4;

        private ErrorsContainer<string> _errorsContainer;
        #endregion

        private bool _useCompareByPartNumber = true;
        private bool _useCompareByPartReference = true;


        // 是否使用按PartNumber对比
        public bool UseCompareByPartNumber
        {
            get => _useCompareByPartNumber;
            set => SetProperty(ref _useCompareByPartNumber, value);
        }

        // 是否使用PartReference对比
        public bool UseCompareByPartReference
        {
            get => _useCompareByPartReference;
            set => SetProperty(ref _useCompareByPartReference, value);
        }

        #region 公共属性
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        public string OutPutPath
        {
            get { return _outPutPath; }
            set { SetProperty(ref _outPutPath, value); }
        }

        public string FilePath1
        {
            get { return _filePath1; }
            set { SetProperty(ref _filePath1, value); }
        }

        public int TitleRow1
        {
            get { return _titleRow1; }
            set { SetProperty(ref _titleRow1, value); }
        }

        public int PartNumberCol1
        {
            get { return _partNumberCol1; }
            set { SetProperty(ref _partNumberCol1, value); }
        }

        public int PartQtyCol1
        {
            get { return _partQtyCol1; }
            set
            {
                SetProperty(ref _partQtyCol1, value, nameof(PartQtyCol1));
                ValidateColumnValue(value, "TextBlockInfo");
            }
        }

        public int PartRefDesCol1
        {
            get { return _partRefDesCol1; }
            set { SetProperty(ref _partRefDesCol1, value); }
        }

        public int PartDescriptionCol1
        {
            get { return _partDescriptionCol1; }
            set { SetProperty(ref _partDescriptionCol1, value); }
        }

        public string FilePath2
        {
            get { return _filePath2; }
            set { SetProperty(ref _filePath2, value); }
        }

        public int TitleRow2
        {
            get { return _titleRow2; }
            set { SetProperty(ref _titleRow2, value); }
        }

        public int PartNumberCol2
        {
            get { return _partNumberCol2; }
            set { SetProperty(ref _partNumberCol2, value); }
        }

        public int PartQtyCol2
        {
            get { return _partQtyCol2; }
            set { SetProperty(ref _partQtyCol2, value); }
        }

        public int PartRefDesCol2
        {
            get { return _partRefDesCol2; }
            set { SetProperty(ref _partRefDesCol2, value); }
        }

        public int PartDescriptionCol2
        {
            get { return _partDescriptionCol2; }
            set { SetProperty(ref _partDescriptionCol2, value); }
        }

        public string Message
        {
            get { return _message; }
            set { SetProperty(ref _message, value); }
        }

        public ErrorsContainer<string> ErrorsContainer
        {
            get
            {
                if (_errorsContainer == null)
                    _errorsContainer = new ErrorsContainer<string>((propName) =>
                    {
                        ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propName));
                    });

                return _errorsContainer;
            }
            set { _errorsContainer = value; }
        }

        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        public bool HasErrors => ErrorsContainer.HasErrors;
        public IEnumerable GetErrors(string propertyName) => ErrorsContainer.GetErrors(propertyName);
        #endregion

        #region 命令
        public DelegateCommand btnGetOutPutPath { get; private set; }
        public DelegateCommand btnGetFile1 { get; private set; }
        public DelegateCommand btnGetFile2 { get; private set; }
        public DelegateCommand btnCompareCommand { get; private set; }
        public DelegateCommand btnShowResultCommand { get; private set; }
        #endregion

        #region 构造函数
        public FileSelectBrowserViewModel(
            IUnityContainer container,
            RegionManager regionManager,
            IDialogService dialogService,
            IEventAggregator ea,
            IExcelReader excelReader,
            IExcelWriter excelWriter,
            IEnumerable<IBomComparisonService> comparisonServices
            //IBomComparisonCoordinator coordinator
            )
        {
            _ea = ea;
            _container = container;
            _regionManager = regionManager;
            _dialogService = dialogService;
            _excelReader = excelReader;
            _excelWriter = excelWriter;
            _comparisonServices = comparisonServices;
            //_coordinator = coordinator;
            InitializeCommands();
        }

        private void InitializeCommands()
        {
            btnGetOutPutPath = new DelegateCommand(GetOutPutPath, CanExecute);
            btnGetFile1 = new DelegateCommand(GetFilePath1, CanExecute);
            btnGetFile2 = new DelegateCommand(GetFilePath2, CanExecute);
            btnCompareCommand = new DelegateCommand(Compare, CanExecute);
            btnShowResultCommand = new DelegateCommand(ShowResult, CanExecute);
        }
        #endregion

        #region 私有方法
        private BomHeaderMap CreateHeaderMap1()
        {
            if (PartNumberCol1 <= 0 || PartQtyCol1 <= 0)
            {
                throw new InvalidOperationException("列配置无效");
            }
            return new BomHeaderMap
            {
                TitleRow = TitleRow1,
                PartNumberCol = PartNumberCol1,
                QuantityCol = PartQtyCol1,
                ReferenceDesignatorCol = PartRefDesCol1,
                DescriptionCol = PartDescriptionCol1
            };
        }

        private BomHeaderMap CreateHeaderMap2()
        {
            if (PartNumberCol2 <= 0 || PartQtyCol2 <= 0)
            {
                throw new InvalidOperationException("列配置无效");
            }
            return new BomHeaderMap
            {
                TitleRow = TitleRow2,
                PartNumberCol = PartNumberCol2,
                QuantityCol = PartQtyCol2,
                ReferenceDesignatorCol = PartRefDesCol2,
                DescriptionCol = PartDescriptionCol2
            };
        }

        private void ValidateColumnValue(int value, string propertyName)
        {
            if (value == 0)
            {
                ErrorsContainer.SetErrors(propertyName, new string[] { "输入值无效" });
            }
            else
            {
                ErrorsContainer.ClearErrors(propertyName);
            }
        }

        private void ShowResult()
        {
            _dialogService.ShowDialog("ShowResultDialog");
        }

        private async void Compare()
        {

            try
            {
                _ea.GetEvent<MessageSentEvent>().Publish("开始对比");

                // 验证文件路径是否有效
                if (string.IsNullOrEmpty(FilePath1) || string.IsNullOrEmpty(FilePath2))
                {
                    //_dialogService.ShowNotification("请先选择两个有效的文件路径！");
                    return;
                }

                // 创建头部映射
                var map1 = CreateHeaderMap1();
                var map2 = CreateHeaderMap2();

                // 使用 IExcelReader 读取数据
                List<BomItem> bomData1 = _excelReader.ReadData(FilePath1, map1);
                List<BomItem> bomData2 = _excelReader.ReadData(FilePath2, map2);

                // 模拟对比逻辑（可以替换为实际的对比服务调用）
                if (bomData1.Count == 0 || bomData2.Count == 0)
                {
                    //dialogService.ShowNotification("读取的 BOM 数据为空，请检查文件内容！");
                    return;
                }

                var result1 = new ComparisonResult();
                var result2 = new ComparisonResult();

                if (UseCompareByPartNumber)
                {
                    var service = _comparisonServices.FirstOrDefault(s => s.GetType().Name == "CompareByPartNumber");
                    if (service != null)
                        result1 = service.CompareBoms(bomData1, bomData2);
                }
                if (UseCompareByPartReference)
                {
                    var service = _comparisonServices.FirstOrDefault(s => s.GetType().Name == "CompareByPartReference");
                    if (service != null)
                        result2 = (service.CompareBoms(bomData1, bomData2));
                }


                // 使用 IExcelWriter 导出结果
                _excelWriter.ComparisonResultByPartNumber = result1.SummaryByPartNumbers;
                _excelWriter.ComparisonResultByPartReference = result2.SummaryByPartReferences;

                // 设置导出路径
                string exportPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                //string exportPath = Path.Combine(OutPutPath, "BomComparisonResult.xlsx");

                _excelWriter.ExportFromPath(OutPutPath, "BomComparisonResult.xlsx");

                // 发布对比完成事件
                _ea.GetEvent<MessageSentEvent>().Publish("对比完成");
                //_dialogService.ShowNotification("BOM 对比完成！");
            }
            catch (Exception ex)
            {
                // _dialogService.ShowNotification($"对比过程中发生错误: {ex.Message}");
            }


        }

        private void GetFilePath1()
        {
            FilePath1 = OpenFileDialogHelper.SelectExcelFile();
        }

        private void GetOutPutPath()
        {
            OutPutPath = OpenFileDialogHelper.SelectFolderPath();
        }

        private void GetFilePath2()
        {
            FilePath2 = OpenFileDialogHelper.SelectExcelFile();
            _ea.GetEvent<MessageSentEvent>().Publish(FilePath2);
        }

        private bool CanExecute()
        {
            return true;
        }
        #endregion
    }
}
